package com.ruoyi.standingbook.evaluate.service.impl;

import org.springframework.stereotype.Service;

import com.ruoyi.common.tools.constant.ERecordConstant;
import com.ruoyi.common.tools.excel.MyExcelUtil;
import com.ruoyi.common.tools.excel.base.MyExcelResult;
import com.ruoyi.common.tools.excel.listener.EvaluateExcelListener;
import com.ruoyi.common.tools.utils.DateUtils;
import com.ruoyi.common.tools.utils.SerialGenerator;
import com.ruoyi.standingbook.evaluate.domain.bo.EvaluateImportBaseBo;
import com.ruoyi.standingbook.evaluate.domain.vo.EvaluateImportDetailVo;
import com.ruoyi.standingbook.evaluate.service.IEvaluateImportBaseService;
import com.ruoyi.standingbook.evaluate.service.IEvaluateImportDetailService;
import com.ruoyi.standingbook.evaluate.service.IEvaluateService;
import com.ruoyi.stat.evaluate.service.IEvaluateStatService;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Service
public class EvaluateExcelService {
	private final IEvaluateService evaluateService;
	private final IEvaluateImportBaseService evaluateImportBaseService;
	private final IEvaluateImportDetailService evaluateImportDetailService;
	private final IEvaluateStatService evaluateStatService;
	/**
	 * 导入excel数据
	 * 
	 * @param bo
	 * @return
	 */
	public Boolean importExcel(EvaluateImportBaseBo bo) {
		// 生成批次号
		final String batchNo = SerialGenerator.generator.nextId();
		bo.setBatchNo(batchNo);

		// excel 处理
		MyExcelResult<EvaluateImportDetailVo> excelResult = MyExcelUtil.getImportExcelData(batchNo, bo.getExcelUrl(),
				new EvaluateExcelListener(batchNo), EvaluateImportDetailVo.class);

		if (null == excelResult) {
			return false;
		}

		// 更新主表状态
		if (excelResult.isSuccess()) {
			bo.setProcessStatus(ERecordConstant.COMMON_STATUS_SUCCESS);
		} else {
			bo.setProcessStatus(ERecordConstant.COMMON_STATUS_ERROR);
		}
		bo.setProcessMsg(excelResult.getAnalysis());
		bo.setAttachMsg(ERecordConstant.ATTACH_UPLOAD_STATUS_NO);
		// 入库主表
		if (this.evaluateImportBaseService.insertByBo(bo)) {
			// 入库子表
			if (!excelResult.getList().isEmpty()) {
				if (!this.evaluateImportDetailService.batchInsertVo(excelResult.getList())) {
					return false;
				}
			}
		} else {
			return false;
		}

		if (excelResult.isSuccess() && !excelResult.getList().isEmpty()) {
			this.evaluateService.batchInsert(excelResult.getList());

			// 获取 发布日期的 最大 和 最小
			excelResult.getList().sort((a, b) -> a.getPublishDate().compareTo(b.getPublishDate()));
			String startTime = DateUtils.getDate(excelResult.getList().get(0).getPublishDate());
			String endTime = DateUtils.getDate(excelResult.getList().get(excelResult.getList().size() - 1).getPublishDate());
			this.evaluateStatService.createStatData(startTime, endTime);
		}

		return true;
	}
}
